import React, {Component} from 'react';
import { StyleSheet, View, Text, Image} from 'react-native';
import * as Color from "../../../lib.xjs/constant/Color";
import * as BizConstant from "../../constant/BizContant";
import HttpHelper from "../../../lib.xjs/helper/HttpHelper";
import {UUID} from "../../../lib.xjs/util/UUID";
import moment from "moment/moment";

import Echarts from 'native-echarts';
import * as ToastAndroid from "react-native/Libraries/Components/ToastAndroid/ToastAndroid.android";
import TouchableItem from "react-navigation/src/views/TouchableItem";
import BizUser from "../../entity/BizUser";

const ic_btn_left   = require('../../../../img/gaqu/ic_btn_left_gray.png');
const ic_btn_right  = require('../../../../img/gaqu/ic_duijiang_play_normal.png');

/** 仓体报表 */
export default class CabinReport extends Component {

    /** 仓体名称 */
    mCabinName;

    /** 仓体ID */
    mCabinId;

    static navigationOptions = ({navigation}) => ({
        title: `${navigation.state.params.cabinName}`,
    });

    constructor(props) {
        super(props);
        this.state = {
            /** 是否正在刷新 */
            mIsRefresh: false,

            /** 搜索开始日期 */
            mSearchStartTime    : new Date().DateAdd('d', -7),
            /** 搜索结束日期 */
            mSearchEndTime      : new Date(),

            /** 报表配置 */
            option              : this.getOption({}),

            /** 数据源 */
            mDatas: {
                allUserNum              : [],
                allCertifiedUserNum     : [],
                allPayedUserNum         : [],
                activeUserNum           : [],
                totalConsumeMoney       : [],
                timeDepositer           : [],
                timeRefunder            : [],
            },
        };
        this.mCabinName = this.props.navigation.state.params.cabinName;
        this.mCabinId   = this.props.navigation.state.params.cabinId;
    }

    /** 从返回数据里面将各项参数按类别排好队 */
    _getDays(datas) : Object{
        let day                 = [];
        let allUserNum          = [];
        let allCertifiedUserNum = [];
        let allPayedUserNum     = [];
        let activeUserNum       = [];
        let totalConsumeMoney   = [];
        let timeDepositer       = [];
        let timeRefunder        = [];

        for(let data of datas){
            let temp_day                     = moment(data.updateTime).toDate().Format("dd").concat("号");
            let temp_allUserNum              = data.allUserNum;              // 注册人数
            let temp_allCertifiedUserNum     = data.allCertifiedUserNum;     // 认证人数
            let temp_allPayedUserNum         = data.allPayedUserNum;         // 交押人数
            let temp_activeUserNum           = data.activeUserNum;           // 运动次数
            let temp_totalConsumeMoney       = data.totalConsumeMoney;       // 运动收费
            let temp_timeDepositer           = data.timeDepositer;           // 交押次数
            let temp_timeRefunder            = data.timeRefunder;            // 退押次数
            let temp_totalDeposit            = data.totalDeposit;
            let temp_totalRefundDeposit      = data.totalRefundDeposit;

            day                  = [...day                 , temp_day                     ];
            allUserNum           = [...allUserNum          , temp_allUserNum              ];
            allCertifiedUserNum  = [...allCertifiedUserNum , temp_allCertifiedUserNum     ];
            allPayedUserNum      = [...allPayedUserNum     , temp_allPayedUserNum         ];
            activeUserNum        = [...activeUserNum       , temp_activeUserNum           ];
            totalConsumeMoney    = [...totalConsumeMoney   , temp_totalConsumeMoney       ];
            timeDepositer        = [...timeDepositer       , temp_timeDepositer           ];
            timeRefunder         = [...timeRefunder        , temp_timeRefunder            ];
        }

        return {
            "day"                   : day,
            "allUserNum"            : allUserNum,
            "allCertifiedUserNum"   : allCertifiedUserNum,
            "allPayedUserNum"       : allPayedUserNum,
            "activeUserNum"         : activeUserNum,
            "totalConsumeMoney"     : totalConsumeMoney,
            "timeDepositer"         : timeDepositer,
            "timeRefunder"          : timeRefunder,
        };
    }

    /** 传入数据生成配置 */
    getOption(datas : Object) : Object {
        return {
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                padding: [
                    15,  // 上
                    0, // 右
                    0,  // 下
                    0, // 左
                ],

                data: ['注册人数', '认证人数', '交押人数', '运动人数', '运动收费', '交押次数', '退押次数']
            },
            grid: {
                top: '20%',
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: datas.day
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '注册人数',
                    type: 'line',
                    smooth: true,
                    // data:[120, 132, 101, 134, 90, 230, 210],
                    data: datas.allUserNum,
                },
                {
                    name: '认证人数',
                    type: 'line',
                    smooth: true,
                    // data:[220, 182, 191, 234, 290, 330, 310],
                    data: datas.allCertifiedUserNum,
                },
                {
                    name: '交押人数',
                    type: 'line',
                    smooth: true,
                    // data:[150, 232, 201, 154, 190, 330, 410],
                    data: datas.allPayedUserNum,
                },
                {
                    name: '运动人数',
                    type: 'line',
                    smooth: true,
                    // data:[320, 332, 301, 334, 390, 330, 320],
                    data: datas.activeUserNum,
                },
                {
                    name: '运动收费',
                    type: 'line',
                    smooth: true,
                    // data:[820, 932, 901, 934, 1290, 1330, 1320],
                    data: datas.totalConsumeMoney,
                },
                {
                    name: '交押次数',
                    type: 'line',
                    smooth: true,
                    // data:[320, 232, 301, 634, 590, 230, 120],
                    data: datas.timeDepositer,
                },
                {
                    name: '退押次数',
                    type: 'line',
                    smooth: true,
                    // data:[20, 32, 101, 34, 9, 30, 12],
                    data: datas.timeRefunder,
                },
            ]
        };
    }

    shouldComponentUpdate(nextProps: Readonly<P>, nextState: Readonly<S>, nextContext: any): boolean {
        if(this.state.option === nextState.option) return false;
        return true;
    }

    componentDidMount(): void {
        let startTime   = this.state.mSearchStartTime;
        let endTime     = this.state.mSearchEndTime;
        this._getDatas(startTime, endTime);
    }

    /** 查上周 */
    _searchLast(){
        let startTime   = this.state.mSearchStartTime.DateAdd('d', -8);
        let endTime     = this.state.mSearchEndTime.DateAdd('d', -8);
        this._getDatas(startTime, endTime);
    }

    /** 查下周 */
    _searchNext(){
        let diff = new Date().DaysBetween(this.state.mSearchEndTime, new Date);
        if(diff <= 1){
            ToastAndroid.show("预测未来? 不闹~", ToastAndroid.SHORT);
            return;
        }
        let startTime   = this.state.mSearchStartTime.DateAdd('d', +8);
        let endTime     = this.state.mSearchEndTime.DateAdd('d', +8);
        this._getDatas(startTime, endTime);
    }

    render() {
        return (
            <View style={{flex: 1, flexDirection: 'column', alignItems: 'center', backgroundColor: Color.windowWhite}}>
                <Echarts ref={'echart'} option={this.state.option} height={400}/>

                <View style={{flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
                    <TouchableItem onPress={() => this._searchLast()}>
                        <Image
                            style={{width:30,height:30, margin: 15,}}
                            resizeMode={Image.resizeMode.contain}
                            source={ic_btn_left}/>
                    </TouchableItem>

                    <View style={{flex: 1, flexDirection: 'column', justifyContent: 'center', alignItems: 'center'}}>
                        <Text style={styles.text}>{this.state.mSearchStartTime.Format("yyyy-MM-dd")}</Text>
                        <Text style={styles.text_divide}>-至-</Text>
                        <Text style={styles.text}>{this.state.mSearchEndTime.Format("yyyy-MM-dd")}</Text>
                    </View>

                    <TouchableItem onPress={() => this._searchNext()}>
                        <Image
                            style={{width:30,height:30, margin: 15,}}
                            resizeMode={Image.resizeMode.contain}
                            source={ic_btn_right}/>
                    </TouchableItem>
                </View>

                <HttpHelper ref={'http'}/>
            </View>
        );
    }

    /** 获取数据 */
    _getDatas = (startDate: Date, endDate: Date): void =>  {
        if (!this.refs.http) return;
        if (!this.refs.echart) return;

        // let head = new Map();
        // head.set("token", "36b4b4dc1e77e51f28b44fa712847a01");

        let head = BizUser.getHeadParam(true);
        let body = new Map();
        body.set("searchStartTime", startDate.Format("yyyy-MM-dd"));
        body.set("searchEndTime",   endDate.Format("yyyy-MM-dd"));
        body.set("cangId",          this.mCabinId);

        this.refs.http.setURL(BizConstant.GET_CABIN_DAY_REPORT)
            .setMethod(HttpHelper.GET)
            .setNotiInfo("")
            .setHeadParams(head)
            .setBodyParams(body)
            .setRequestId(UUID.getOne())
            .setListener((responseCode: number, res: Object) => {
                if (responseCode !== HttpHelper.RESPONSE_SUCCESS) return;
                if (!res.data) return;

                // 初始化全局变量
                let datas   = res.data;
                let result  = this._getDays(datas);
                let option  = this.getOption(result);

                this.setState({
                    option : option,
                    mSearchStartTime: startDate,
                    mSearchEndTime: endDate,
                });
            })
            .setTimeout(10 * 1000)
            .start(false);
    };
}

const styles = StyleSheet.create({
    text: {
        color: '#099eff',
        margin: 5,
        fontSize: 15,
    },
    text_divide: {
        color: '#099eff',
        fontSize: 15,
    }
});
